from sqlalchemy.orm import Session
from sqlalchemy.exc import IntegrityError

from app.models.like import Like
from app.models.comment import Comment
from app.models.generation_job import GenerationJob
from app.schemas.comment import CommentCreate

def like_job(db: Session, *, user_id: int, job_id: int) -> GenerationJob | None:
    """
    用户点赞作品
    """
    # 检查作品是否存在
    job = db.query(GenerationJob).filter(GenerationJob.id == job_id).first()
    if not job:
        return None
    
    # 检查是否已经点赞
    existing_like = db.query(Like).filter(
        Like.user_id == user_id, 
        Like.job_id == job_id
    ).first()
    
    if existing_like:
        return job  # 已经点赞了，直接返回
    
    # 创建点赞记录
    like = Like(user_id=user_id, job_id=job_id)
    db.add(like)
    
    # 更新点赞计数
    job.likes_count += 1
    db.add(job)
    
    try:
        db.commit()
        db.refresh(job)
        return job
    except IntegrityError:
        db.rollback()
        return job  # 并发情况下可能已经点赞了

def unlike_job(db: Session, *, user_id: int, job_id: int) -> GenerationJob | None:
    """
    用户取消点赞作品
    """
    # 检查作品是否存在
    job = db.query(GenerationJob).filter(GenerationJob.id == job_id).first()
    if not job:
        return None
    
    # 查找点赞记录
    like = db.query(Like).filter(
        Like.user_id == user_id, 
        Like.job_id == job_id
    ).first()
    
    if not like:
        return job  # 没有点赞记录，直接返回
    
    # 删除点赞记录
    db.delete(like)
    
    # 更新点赞计数
    if job.likes_count > 0:
        job.likes_count -= 1
    db.add(job)
    
    db.commit()
    db.refresh(job)
    return job

def create_comment(db: Session, *, user_id: int, job_id: int, comment_in: CommentCreate) -> Comment:
    """
    创建评论
    """
    # 检查作品是否存在
    job = db.query(GenerationJob).filter(GenerationJob.id == job_id).first()
    if not job:
        raise ValueError("Job not found")
    
    comment = Comment(
        content=comment_in.content,
        user_id=user_id,
        job_id=job_id
    )
    
    db.add(comment)
    db.commit()
    db.refresh(comment)
    return comment

def get_comments_for_job(db: Session, *, job_id: int, skip: int = 0, limit: int = 100) -> list[Comment]:
    """
    获取作品的评论列表
    """
    return (
        db.query(Comment)
        .filter(Comment.job_id == job_id)
        .order_by(Comment.created_at.desc())
        .offset(skip)
        .limit(limit)
        .all()
    )

def check_user_liked_job(db: Session, *, user_id: int, job_id: int) -> bool:
    """
    检查用户是否已点赞作品
    """
    like = db.query(Like).filter(
        Like.user_id == user_id, 
        Like.job_id == job_id
    ).first()
    return like is not None
